package com.kuang.demo.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.kuang.demo.bean.acgBeanVo.BaseData;
import com.kuang.demo.bean.lhf.Ad;
import com.kuang.demo.bean.lhf.AdExample;
import com.kuang.demo.mapper.AdMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class AdServiceImp implements AdService{

    @Autowired
    AdMapper adMapper;

    @Override
    public BaseData queryAdList(Integer page, Integer limit, String sort, String order, String name, String content) {
        //预编译的时候增加分页的sql语句
        PageHelper.startPage(page, limit);
        //设置排序的条件
        AdExample adExample = new AdExample();
        if (name != null && !"".equals(name)){
            adExample.createCriteria().andNameLike("%"+name+"%");
        }
        if (content != null && !"".equals(content)){
            adExample.createCriteria().andNameLike("%"+content+"%");
        }
        adExample.setOrderByClause(sort+" "+order);
        //获取查询结果
        List<Ad> ads = adMapper.selectByExample(adExample);
        //可以在查询完成后获得pageInfo → 根据查询结果获得总条目数total
        PageInfo<Ad> adPageInfo = new PageInfo<>(ads);
        long total = adPageInfo.getTotal();

        //所需数据封装并返回
        return BaseData.data(ads,total);
    }

    @Override
    public void updateAd(Ad ad) {
        AdExample adExample = new AdExample();
        adExample.createCriteria().andIdEqualTo(ad.getId());
        adMapper.updateByExample(ad,adExample);
    }

    @Override
    public void deletedelete(Ad ad) {
        AdExample adExample = new AdExample();
        adExample.createCriteria().andIdEqualTo(ad.getId());
        adMapper.deleteByExample(adExample);
    }

    @Override
    public Ad create(Ad ad) {
        ad.setAddTime(new Date());
        ad.setUpdateTime(new Date());
        ad.setDeleted(false);
        adMapper.insert(ad);
        return ad;
    }
}
